package com.fyy.sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author fyy
 * @Description Sentinel熔断降级配置代码实现
 * @Date 2021/7/15 9:02
 */
@RestController
public class DegradeController {

    @SentinelResource(value = "TestDegrade", blockHandler = "exHandler")
    @RequestMapping("/testDegrade")
    public String hello() throws InterruptedException {
        Thread.sleep(1000);
        return "hello,Sentinel";
    }

    public String exHandler(BlockException e) {
        System.out.println(e.getMessage());
        return "系统繁忙！";
    }

    //定义熔断降级规则
    @PostConstruct
    public void initDegradeRule() {
        //创建存放熔断降级规则的集合
        List<DegradeRule> rules = new ArrayList<>();
        //创建熔断降级规则
        DegradeRule rule = new DegradeRule();
        //定义资源名
        rule.setResource("TestDegrade");
        //阈值 秒
        rule.setCount(0.001);
        //定义规则类型
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
        //定义降级时间,秒级
        rule.setTimeWindow(2);
        //加入集合
        rules.add(rule);
        //加载熔断降级规则
        DegradeRuleManager.loadRules(rules);
    }

}
